package cn.com.controller;

import cn.com.beans.CollegeInfo;
import cn.com.beans.FractionInfo;
import cn.com.beans.VipActivateReturn;
import cn.com.service.CollegeInfoService;
import cn.com.service.FractionInfoService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.Year;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/insertLine")
public class InsertLineController {
    @Resource
    private CollegeInfoService collegeInfoService;
    @Resource
    private FractionInfoService fractionInfoService;

    @GetMapping
    public String home(){
        return "Insert/InsertLine";
    }

    @GetMapping("/inquireSchool/{coNameValue}")
    @ResponseBody
    public List<VipActivateReturn> inquireSchool(@PathVariable String coNameValue){
        CollegeInfo collegeInfo = new CollegeInfo();
        collegeInfo.setCoName(coNameValue);
        List<CollegeInfo> activationCodes = collegeInfoService.findAll(collegeInfo);
        VipActivateReturn vipActivateReturn = new VipActivateReturn();
        if(activationCodes.size() == 0){
            vipActivateReturn.setMsg("校名输入错误");
            vipActivateReturn.setType(0);
        }else{
            vipActivateReturn.setMsg("校名输入正确");
            vipActivateReturn.setType(1);
        }
        List<VipActivateReturn> list = new ArrayList<>();
        list.add(vipActivateReturn);
        return list;
    }

    @PostMapping("/insert")
    @ResponseBody
    public Map<String,Object> insert(HttpServletRequest request){
        Map<String,Object> result = new HashMap<>();
        String coName = request.getParameter("coName");
        Integer frType = Integer.valueOf(request.getParameter("frType"));
        Integer year = Integer.valueOf(request.getParameter("year"));
        Integer grade = Integer.valueOf(request.getParameter("grade"));
        CollegeInfo collegeInfo = new CollegeInfo();
        collegeInfo.setCoName(coName);
        List<CollegeInfo> activationCodes = collegeInfoService.findAll(collegeInfo);
        Integer coId = activationCodes.get(0).getCoId();
        FractionInfo fractionInfo = new FractionInfo();
        fractionInfo.setFrYear(year);
        fractionInfo.setFrType(frType);
        fractionInfo.setFrScore(grade);
        fractionInfo.setFrCoid(coId);
        FractionInfo info = fractionInfoService.findAll(fractionInfo);
        if(info != null){
            result.put("code",0);
            result.put("msg","已经存在,添加失败");
            return result;
        }
        int i = fractionInfoService.insert(fractionInfo);
        if(i == 1){
            result.put("code",1);
            result.put("msg","添加成功");
            return result;
        }else{
            result.put("code",2);
            result.put("msg","添加失败");
            return result;
        }
    }
}
